﻿using PwjCy.Lite.Common;
using PwjCy.Lite.Core;
using PwjCy.Lite.Core.Imp;
using PwjCy.Lite.Storage;
using PwjCy.Lite.Storage.Imp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PwjCy.Lite.Persistence.Imp
{
    public class PersisterMapping : IPersisterMapping
    {
        private bool _IsRegisterPersistenceDriver { get; set; }
        private static StorageContexts _StorageContexts = LiteCoreHelper.GetObjectSetting<StorageContexts>(LiteCoreHelper.StorageConfigPath);
        public void RegisterPersitenceDriver()
        {
            if (!_IsRegisterPersistenceDriver)
            {
                try
                {
                    foreach (var _StorageContext in _StorageContexts.StorageConfigList)
                    {
                        HashCacheHelper.Instance.AddCache<IStorageContext>(_StorageContext, _StorageContext.Name);
                        HashCacheHelper.Instance.AddCache<IPersistenceDriver>(ReflectHelper.Instance.CreateInstance<IPersistenceDriver>(_StorageContext.PersistenceDriver), _StorageContext.Name);
                        HashCacheHelper.Instance.AddCache<IDriver>(ReflectHelper.Instance.CreateInstance<IDriver>(_StorageContext.DriverClass), _StorageContext.Name);
                    }
                }
                catch (Exception ex)
                {
                    ServiceHub.LoggerService.Error("RegisterPersistenceDriver Error:{0}", ex);
                }
            }
            this._IsRegisterPersistenceDriver = true;
        }
        /// <summary>
        /// 获取数据库驱动
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="storageAlias"></param>
        /// <returns></returns>
        public T GetDirver<T>(string storageAlias)
        {
            return HashCacheHelper.Instance.GetCache<T>(storageAlias);
        }
    }
}
